/*
 * The Login dialog
 */
package gui;

import Protocol.InlogResponsePacket;
import client.Startup;
import config.Content;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import javax.swing.*;

/**
 * The login dialog
 * @author Kay van Bree
 */
public class LoginScreen extends JFrame implements ActionListener {
	private JLabel labelUsername, labelPassword, labelText, labelError, labelFooter;
	private JTextField fieldUsername;
	private JPasswordField fieldPassword;
	private JButton buttonLogin, buttonCancel, buttonSettings;
	private JPanel errorPanel, textPanel, footerPanel, formPanel, imagePanel;
	private Image image;
	private Color bgColor;
	private final FlowLayout layout;
	boolean login = false; // Did we log in?
	
	/**
	 * Sets the Dialogs frame and builds the form
	 * @author Kay van Bree
	 * @since 0.1
	 */
	public LoginScreen(){
		Content.log.println("Loading login screen...");
		this.bgColor = Color.WHITE;
		setTitle("Log in");
		setSize(350,400);
		setResizable(false);
		setLocationRelativeTo(null);
		layout = new FlowLayout();
		layout.setVgap(0);
		setLayout(layout);
		// setModalityType(Dialog.ModalityType.TOOLKIT_MODAL);
		Startup.client = null;
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		buildForm();
		setIcons();
		
		setVisible(true);
	}
	
	/*
	 * Set the icons
	 * @author Kay van Bree
	 */
	public void setIcons(){
		ArrayList imageList = new ArrayList();
		imageList.add(Toolkit.getDefaultToolkit().getImage("bunie50x50.png"));
		setIconImages(imageList);
	}
	
	/**
	 * Builds the login form
	 * @author Kay van Bree
	 * @since 0.1
	 */
	private void buildForm(){
		// Draw the image
	//	String dir = System.getProperty("user.dir") + "/src/client";
		image = Toolkit.getDefaultToolkit().getImage("loginheader.JPG");
		imagePanel = new JPanel(){
			@Override
			public void paintComponent(Graphics g){
				g.drawImage(image, 0,0,350,100, this);
			}
		};
		imagePanel.setPreferredSize(new Dimension(350, 100));
		
		add(imagePanel);
		
		// The text 'area'
		textPanel = new JPanel();
		textPanel.setPreferredSize(new Dimension(305, 50));	
		labelText = new JLabel("<html>Use this form to log in. To change the IP/URL or port of<br />the server, click Settings.</html>",
				SwingConstants.LEFT);
		textPanel.add(labelText);
		add(textPanel);
		
		formPanel = new JPanel(new FlowLayout());
		formPanel.setPreferredSize(new Dimension(350, 100));
		labelUsername = new JLabel("Username");
		formPanel.add(labelUsername);
		fieldUsername = new JTextField(20);
		formPanel.add(fieldUsername);
		labelPassword = new JLabel("Password");
		formPanel.add(labelPassword);
		fieldPassword = new JPasswordField(20);
		formPanel.add(fieldPassword);
		
		// Buttons
		buttonLogin = new JButton("Login");
		buttonLogin.addActionListener(this);
		formPanel.add(buttonLogin);
		getRootPane().setDefaultButton(buttonLogin);
		buttonSettings = new JButton("Settings");
		buttonSettings.addActionListener(this);
		formPanel.add(buttonSettings);
		buttonCancel = new JButton("Close");
		buttonCancel.addActionListener(this);
		formPanel.add(buttonCancel);
		
		add(formPanel);
		
		// Area for error messages
		errorPanel = new JPanel();
		errorPanel.setBorder(BorderFactory.createLineBorder(Color.GRAY));
		errorPanel.setPreferredSize(new Dimension(300, 85));
		labelError = new JLabel("", SwingConstants.LEFT);
		labelError.setPreferredSize(new Dimension(280, 80));
		labelError.setVerticalAlignment(SwingConstants.TOP);
		errorPanel.add(labelError);
		add(errorPanel);
		
		// The footer area
		footerPanel = new JPanel();
		footerPanel.setPreferredSize(new Dimension(300, 20));	
		labelFooter = new JLabel("<html><small>Software designed by ISM2Ia - DSW</small></html>",
				SwingConstants.LEFT);
		footerPanel.add(labelFooter);
		add(footerPanel);
	}
	
	/**
	 * Handles performed actions
	 * @param e The source
	 */
	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == buttonLogin) performLogin();
		if(e.getSource() == buttonSettings) performSettingsDialog();
		if(e.getSource() == buttonCancel) performExit();
	}
	
	/**
	 * Exit the complete application.
	 * @author Kay van Bree
	 */
	public void performExit(){
		dispose();
		System.exit(0);
	}
	
	/**
	 * Open a new Settings Dialog
	 * @author Kay van Bree
	 */
	private void performSettingsDialog(){
		SettingsDialog settings = new SettingsDialog();
	}

	/**
	 * Do the login
	 * @author Kay van Bree
	 */
	private void performLogin() {
		login = false;
		boolean isAdmin = false;
		
		// Load config & Create connection
		Content.config.loadConfigs();
		// Check if connection worked
		if(!Content.connection.isConnected()){
			Content.connection.setConnection(Content.config.ip, Content.config.port);
		}
		if(!Content.connection.isConnected()){
			setError("<html>Error: Couldn't connect. Please "
				+ " <br />check your settings!</html>");
		} else {
			// Get fields
			String username = fieldUsername.getText();
			String password = new String(fieldPassword.getPassword());

			// Check if the fields are set
			if(username.equals("") || password.equals("")){
				setError("<html>Please fill in <b>both</b> Username and password</html>");
			} else {
				// Check if information is correct
				InlogResponsePacket response = Content.connection.login(username, password);
				if(response.getInlogStatus() == InlogResponsePacket.INLOGSUCCES){
					if(response.getTypeOfClient() == 1){ 
						isAdmin = true;
					}
					login = true;
				} else {
					setError("<html>This user/password has not been found!</html>");
				}
			}
		}
		
		// If fields are set, do stuff
		if(login == true){
			if(isAdmin){
				Content.log.println("Logged in as Admin.");
				// In this case the login went fine.
				Startup.client = new MasterClient("Bunie MasterClient");
			} else {
				Content.log.println("Login succesfull.");
				Startup.client = new Client("Bunie Client");
			}
			Startup.client.run();
			setVisible(false);
		}
	}
		
	/**
	 * Encrypts the password
	 * @param password
	 * @return Encrypted password
	 */
	public static String encrypt(String password){
		try {
			MessageDigest digest = MessageDigest.getInstance("MD5");
			digest.update(password.getBytes(), 0, password.length());
			String md5 = new BigInteger(1, digest.digest()).toString(16);
			return md5;
		} catch (NoSuchAlgorithmException ex) {
			return null;
		}
	}
	
	/**
	 * This displays an error message, with a border
	 * @param text 
	 */
	private void setError(String text){
		labelError.setText(text);
		Content.log.println("Login-error: " + text);
	}
}
